import React, { Component } from 'react';
import { Form, Button, message } from 'antd';
import http from '../utils/http';
import '../assets/css/login.scss';
import md5 from 'js-md5';
import ev from '../utils/event'
import bg from '../assets/img/bg.png'
const FormItem = Form.Item;
const createForm = Form.create;

class Login extends Component {
    
    state = {
        loading: false,
    }

    handleSubmit = () => {
        this.props.form.validateFields(async(errors, values) => {
            if (!!errors) {
                return;
            }
            this.setState({
                loading: true
            })
            values.password = md5(values.password);
            let _data = await http('post', '/login', values);
            if(_data.data.code === 200) {
                message.success('登录成功', 2, () => {
                    localStorage.setItem('token', _data.data.token);
                    this.props.history.push('/main/home');
                })
            } else {
                this.setState({
                    loading: false
                })
            }
        });
        
    }

    // 验证token
    checkToken = async() => {
        await http('post', '/checkToken');
    }

    componentDidMount() {
        ev.emit('change', '123')
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="bg-login">
                <img src={bg} alt="beijintupian"/>

                <div  className="login-box">
                    <div className="title">登   录</div>
                    <Form>
                        <FormItem>
                            {getFieldDecorator('username', {
                                rules: [{ required: true, message: 'Please input your username!' }],
                            })(
                                <input placeholder="用户名" id="username" type="text"/>
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('password', {
                                rules: [{ required: true, message: 'Please input your Password!' }],
                            })(
                                <input placeholder="密码" id="password" type="password"/>
                            )}
                        </FormItem>
                        <FormItem>
                            <Button type="primary" onClick={this.handleSubmit} loading={this.state.loading} className="login-form-button">
                                登录
                            </Button>
                        </FormItem>
                    </Form>
                </div>
            </div>
            
        )
    }
}

Login = createForm()(Login);

export default Login;
